/*
 * Copyright &copy; 2011-2020 lnint Inc. All right reserved.
 * 
 * 修改信息：【与SVN提交信息一致】
 * A: 新增类 赵庆辉 2015-3-12 9:06:26
 */
package com.lnint.jess.common.utils;

import com.google.zxing.common.BitMatrix;

import javax.imageio.ImageIO;
import java.io.File;
import java.io.OutputStream;
import java.io.IOException;
import java.awt.image.BufferedImage;

/**
 * <P>根据图形矩阵生成图片文件</P>
 * 
 * @version 1.0
 * @author 赵庆辉 2015-3-12 9:06:26
 * @since JDK 1.6
 */
public final class MatrixToImageWriter {
	private static final int BLACK = 0xFF000000;
	private static final int WHITE = 0xFFFFFFFF;
	
	private MatrixToImageWriter() {}
	
	/**
	 * <P>根据图形矩阵生成缓存图片</P>
	 * 
	 * @param matrix 图形矩阵.
	 * @return image
	 */
	public static BufferedImage toBufferedImage(BitMatrix matrix) {
		int width = matrix.getWidth();
		int height = matrix.getHeight();
		BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
		for (int x = 0; x < width; x++) {
			for (int y = 0; y < height; y++) {
				image.setRGB(x, y, matrix.get(x, y) ? BLACK : WHITE);
			}
		}
		return image;
	}
	
	/**
	 * <P>将图形矩阵按指定的格式、文件生成图片</P>
	 * 
	 * @param matrix 图形矩阵
	 * @param format 图片格式
	 * @param file 图片文件
	 * @return void
	 */
	public static void writeToFile(BitMatrix matrix, String format, File file)
	throws IOException {
		BufferedImage image = toBufferedImage(matrix);
		if (!ImageIO.write(image, format, file)) {
			throw new IOException("Could not write an image of format " + format + " to " + file);
		}
	}
	
	/**
	 * <P>将图形矩阵按指定图片格式写入到输出流</P>
	 * 
	 * @param matrix 图形矩阵
	 * @param format 图片格式
	 * @param stream 输出流
	 * @return void
	 */
	public static void writeToStream(BitMatrix matrix, String format, OutputStream stream)
	throws IOException {
		BufferedImage image = toBufferedImage(matrix);
		if (!ImageIO.write(image, format, stream)) {
			throw new IOException("Could not write an image of format " + format);
		}
	}

}